package cn.tedu.fy.pethome.service.impl;

import cn.tedu.fy.pethome.ex.ServiceException;
import cn.tedu.fy.pethome.mapper.GoodsMapper;
import cn.tedu.fy.pethome.pojo.dto.PetAddNewDTO;
import cn.tedu.fy.pethome.pojo.entity.Goods;
import cn.tedu.fy.pethome.pojo.vo.GoodsDetailVO;
import cn.tedu.fy.pethome.pojo.vo.GoodsListItemsVO;
//import cn.tedu.fy.pethome.repo.IPetRepository;
import cn.tedu.fy.pethome.service.IPetService;
import cn.tedu.fy.pethome.web.DataEnable;
import cn.tedu.fy.pethome.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商品业务的实现类
 *
 * @author KJ2476
 * @date 2022/7/21
 */
@Slf4j
@Service
public class PetServiceImpl implements IPetService {
    @Autowired
    GoodsMapper goodsMapper;
//    @Autowired
//    IPetRepository petRepository;

    /**
     * 添加宠物
     *
     * @param petAddNewDTO 待添加的宠物信息
     */
    @Override
    public void petAddNew(PetAddNewDTO petAddNewDTO) {
        log.debug("开始处理添加宠物的业务,参数：{}", petAddNewDTO);
        String name = petAddNewDTO.getGoodsName();
        GoodsDetailVO detailById = goodsMapper.getByName(name);
        if (detailById != null) {
            String msg = "商品名为" + name + "的商品已经存在,商品名称不能重复";
            log.debug(msg);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,msg);
        }
        Goods goods = new Goods();
        BeanUtils.copyProperties(petAddNewDTO, goods);

        // 补全剩余的属性
        goods.setStockThreshold(0);
        goods.setUnit("只");
        goods.setBrandId(0L);
        goods.setBrandName("无");
        goods.setSales(0);
        goods.setCommentCount(0);
        goods.setPositiveCommentCount(0);
        goods.setIsDeleted(DataEnable.DISABLE);
        goods.setIsRecommend(DataEnable.ENABLE);
        // 默认设置未审核
        goods.setIsChecked(DataEnable.DISABLE);
        goods.setCheckUser("无");


        int rows = goodsMapper.insert(goods);
        if (rows != 1) {
            String msg = "添加失败，服务器忙，请稍后再试!";
            log.debug("添加宠物失败，插入的结果不为1，而是{}", rows);
            throw new ServiceException(ServiceCode.ERR_INSERT,msg);
        }
    }

    @Override
    public List<GoodsListItemsVO> list() {
        log.debug("开始处理查询商品列表的业务");
        return goodsMapper.list();
    }

    @Override
    public List<GoodsListItemsVO> getByCategoryId(Long cid) {
        log.debug("开始处理根据类别名称查询商品列表的业务");
        return goodsMapper.getByCategoryId(cid);
    }

    @Override
    public List<GoodsListItemsVO> getByWd(String wd) {
        log.debug("开始处理根据关键词查询商品列表的业务");
        return goodsMapper.getByWd(wd);
    }

    @Override
    public GoodsDetailVO getById(String id) {
        log.debug("开始处理根据id查询商品详情的业务");
        return goodsMapper.getById(id);
    }
}
